package mybatis;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import mybatis.handler.UserAndTimeHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;

/**
 * @see TransactionAutoConfiguration
 * @see DataSourceTransactionManagerAutoConfiguration
 * @see com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration
 */
@Configuration(proxyBeanMethods = false)
public class MybatisPlusAutoConfiguration {
    /**
     * 用户和时间字段自动填充
     */
    @Bean
    @ConditionalOnClass(User.class)
    public MetaObjectHandler userAndTimeHandler() {
        return new UserAndTimeHandler();
    }

    @Bean
    MybatisPlusInterceptor mybatisPlusInterceptor() { // 插件
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(paginationInnerInterceptor());
        interceptor.addInnerInterceptor(blockAttackInnerInterceptor());
        return interceptor;
    }

    PaginationInnerInterceptor paginationInnerInterceptor() { // 分页
        return new PaginationInnerInterceptor();
        // return new PaginationInnerInterceptor(DbType.MYSQL);
    }

    BlockAttackInnerInterceptor blockAttackInnerInterceptor() { // 防止全表更新与删除
        return new BlockAttackInnerInterceptor();
    }

    // @Bean
    // public ISqlInjector sqlInjector() {
    //     return new DefaultSqlInjector() {
    //         @Override
    //         public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
    //             List<AbstractMethod> methodList = super.getMethodList(mapperClass);
    //             methodList.add(new LogicDeleteByIdWithFill());
    //             return methodList;
    //         }
    //     };
    // }

    @Bean
    ConfigurationCustomizer configurationCustomizer() {
        // Map 下划线自动转驼峰
        return i -> i.setObjectWrapperFactory(new MybatisMapWrapperFactory());
    }
}